#encoding=utf8
'''
Created on Aug 10, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django import forms
from qa_info.models import DevQAInfo, DevQANote, ReleaseQAInfo, ReleaseQANote
from prd_order.models import JOB_FAMILY_MAP
from utils import api_call
import settings
from core.widgets import CustomTextarea
from suit.widgets import EnclosedInput, SuitDateWidget
from app_info.models import AppVersion
from django.contrib.admin.widgets import FilteredSelectMultiple
from sdk_info.models import SDKVersion


class BaseQANoteInlineForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(BaseQANoteInlineForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            self.fields['content'] = forms.CharField(required=True, label='Notes',
                widget=CustomTextarea({'readonly': 'readonly'}))


class DevQANoteInlineForm(BaseQANoteInlineForm):

    class Meta:
        model = DevQANote


class ReleaseQANoteInlineForm(BaseQANoteInlineForm):

    class Meta:
        model = ReleaseQANote


class BaseQAInfoForm(forms.ModelForm):

    error_messages = {'required': 'This field is required.'}

    tester = forms.MultipleChoiceField(required=False, label='Tester')

    def __init__(self, *args, **kwargs):
        super(BaseQAInfoForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            choices = ()
            fid = JOB_FAMILY_MAP.get('Dev QA')
            data = api_call('%s%s' % (settings.TMS_DOMAIN, settings.TMS_GET_STAFFING),
                {'jobfamily': fid})
            if data.get('code') == 1:
                list = []
                staffs = data['staffs']
                for s in staffs:
                    list += s['list']
                choices += tuple([('%s - %s' % (x['EmployeeCode'], x['ChineseName']),
                                   '%s - %s' % (x['EmployeeCode'], x['ChineseName']))\
                                  for x in list])
            self.fields['tester'].choices = choices
            if self.instance.tester:
                initial = self.instance.tester.split(',')
                self.initial['tester'] = initial

    class Media:
        js = ('chosen/chosen.jquery.min.js', 'base/js/custom_devqa_admin.js',
            'base/js/RelatedObjectLookups.js')
        css = {'all': ('chosen/chosen.min.css',)}

    def clean_tester(self):
        tester = self.cleaned_data.get('tester')
        return ','.join(tester) if tester else None


class DevQAInfoForm(BaseQAInfoForm):

    class Meta:
        model = DevQAInfo
        widgets = {'time_spent': EnclosedInput(append='man hours'),
                   'real_clear_at': SuitDateWidget}

    def clean_status(self):
        status = self.cleaned_data.get('status')
        if self.instance and self.instance.pk:
            if not status:
                raise forms.ValidationError(self.error_messages['required'])
        return status

    def clean_version(self):
        version = self.cleaned_data.get('version')
        app = self.cleaned_data.get('app')
        if version and app:
            if not AppVersion.objects.filter(app=app, code=version).exists():
                raise forms.ValidationError('App with selected version does not exists.')
            if DevQAInfo.objects.filter(app=app, version=version)\
                .exclude(pk=self.instance.pk).exclude(status='X').exists():
                raise forms.ValidationError('Request with selected app & version alreay exists.')
        return version

    def clean_app(self):
        app = self.cleaned_data.get('app')
        if app:
            if not app.flurry_key:
                raise forms.ValidationError('Flurry key is not ready.')
#             if not app.ga_key:
#                 raise forms.ValidationError('GA Key is not ready.')
            if not app.quantcast_key:
                raise forms.ValidationError('QuantCast key is not ready.')
        return app


class ReleaseQAInfoForm(BaseQAInfoForm):

    class Meta:
        model = ReleaseQAInfo
        widgets = {'studio_sdk': forms.CheckboxInput,
                   'about_page': forms.CheckboxInput,
                   'version_checker': forms.CheckboxInput,
                   'time_spent': EnclosedInput(append='man hours'),
                   'real_clear_at': SuitDateWidget}
